#pragma once 

#include<iostream>
#include<string>
#include<fstream>
#include<unordered_map>
#include"Logger.hpp"

static const std::string sep = ": ";

class Dictionary
{
private:
    //加载
    void LoadConf()
    {
        //相当于就是打开文件
        std::ifstream in(_path);
        if(!in.is_open())
        {
            LOG(LogLevel::ERROR) <<"open file error" << _path;
            return;
        }
        std::string line;
        while(std::getline(in ,line))
        {
            LOG(LogLevel::DEBUG) << "load dice message: " << line;
            //cat: 猫
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                //没有找到
                LOG(LogLevel::WARNING) << "format error: " << line;
                continue;//格式错误就不处理当前的，需要继续向下处理
            }
            std::string word = line.substr(0 ,pos);//获取从下标从0 开始长度为pos 的子串
            std::string value = line.substr(pos+sep.size());
            if(word.empty() || value.empty())
            {
                LOG(LogLevel::WARNING) << "format error , word or value is empty: " << line;
                continue; 
            }
            //将获取的中英文的映射关系放入map 中
            _dict.insert(std::make_pair(word , value));
        }
        //关闭文件
        in.close();
    }
public:
    //构造
    Dictionary(const std::string& path ) :_path(path)
    {
        LOG(LogLevel::INFO) << "construct Dictionary obj";
        LoadConf();
    }

    std::string Translate(const std::string& word , const std::string& whoip , uint16_t whoport)
    {
        (void)whoip;
        (void)whoport;
        auto iter = _dict.find(word);
        if(iter == _dict.end())
        {
            return "Unknown";
        }
        return iter->first + "->" + iter->second;
    }
    ~Dictionary(){}
private:
    std::string _path;
    std::unordered_map<std::string , std::string> _dict;
};